package com.cy.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {
    //假设这个是存储数据的数据库
    private List<Map<String,Object>> dblist = new ArrayList<>();

    public AjaxController(){
        Map<String ,Object> map = new HashMap<>();
        map.put("id","0909");
        map.put("name","道丶诚某");
        map.put("parentId",null);   //parentId为null则表示它是1级分类
        map.put("remark","名字相关类");
        map.put("createdTime",new Date());
        dblist.add(map);
    }

    @GetMapping("/doAjaxGet")
    public List<Map<String,Object>> doAjaxGet(){
        System.out.println(dblist);
        return dblist;
    }

    @PostMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String,Object> map){
        map.put("createTime", new Date());
        dblist.add(map);
        return "save ok";
    }

    @DeleteMapping("/doAjaxDelete")
    public String doAjaxDelete(String id){
        //获取迭代器对象，然后迭代list集合，找到id对应的元素，进行删除操作
        Iterator<Map<String, Object>> it = dblist.iterator();
        while (it.hasNext()){
            Map<String, Object> map = it.next();
            if (map.get("id").equals(id)){
                it.remove();//通过id将其删除
            }
        }
        return "delete ok";
    }

    @PutMapping("/doAjaxUpdate")
    public String doAjaxUpdate(@RequestParam Map<String,Object> update){

        Iterator<Map<String, Object>> it = dblist.iterator();
        while (it.hasNext()){
            Map<String, Object> map = it.next();
            if (map.get("id").equals(update.get("id"))){
                map.put("name", update.get("name"));
                map.put("remark", update.get("remark"));
            }
        }

        return "update ok";
    }
}
